<!DOCTYPE html>
<html class="x-admin-sm">

<head>
    <meta charset="UTF-8">
    <title>添加菜品</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
    <link rel="stylesheet" href="css/font.css">
    <link rel="stylesheet" href="css/xadmin.css">
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="js/xadmin.js"></script>
    <script type="text/javascript" src="js/cookie.js"></script>
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>
<div class="x-body">
    <form class="layui-form">
        <div class="layui-form-item">
            <label for="name" class="layui-form-label">
                <span class="x-red">*</span>菜名
            </label>
            <div class="layui-input-inline">
                <input type="text" id="name" name="foodName" required="" lay-verify="name" autocomplete="off"
                       class="layui-input" autofocus="autofocus">
            </div>
            <div class="layui-form-mid layui-word-aux">
                <span class="x-red">*</span>不能少于两个字符
            </div>
        </div>

        <div class="layui-form-item">
            <label for="price" class="layui-form-label">
                <span class="x-red">*</span>价格
            </label>
            <div class="layui-input-inline">
                <input type="text" id="price" name="foodPrice" lay-verify="number" autocomplete="off"
                       class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label for="stock" class="layui-form-label">
                <span class="x-red">*</span>库存
            </label>
            <div class="layui-input-inline">
                <input type="text" id="stock" name="foodStock" required="" lay-verify="number" autocomplete="off"
                       class="layui-input"
                       value="999">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">
                <span class="x-red">*</span>类别
            </label>
            <div class="layui-input-inline" lay-filter="select_cook">
                <select id="select_c" name="fccId" lay-verify="required">

                </select>
            </div>
            <div class="layui-input-inline" lay-filter="select_type">
                <select id="select_t" name="ftcId" lay-verify="required">

                </select>
            </div>
        </div>
        <!-- 选择属性 -->
        <div class="layui-form-item">
            <label class="layui-form-label">
                <span class="x-red"></span>属性
            </label>
            <div class="layui-input-block" id="div_material">
                <input type="checkbox" name="like[write]" title="猪">
                <input type="checkbox" name="like[read]" title="牛">
                <input type="checkbox" name="like[dai]" title="羊">
            </div>
        </div>

        <div class="layui-form-item">
            <label for="" class="layui-form-label">
                <span class="x-red">*</span>上传图片
            </label>
            <div class="layui-input-block">
                <button type="button" class="layui-btn layui-btn-normal" id="btn1">
                    <i class="layui-icon">&#xe67c;</i>选择图片
                </button>
                <span id="span_u"></span>
                <input id="input_u" class="layui-hide" name="foodImage" lay-verify="pic"/>
                <button type="button" class="layui-btn" id="btn2">开始上传</button>
                <div class="layui-upload-list">
                    <img class="layui-upload-img" id="img1"/>
                    <p id="demoText"></p>
                </div>
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label for="description" class="layui-form-label">
                描述
            </label>
            <div class="layui-input-block">
						<textarea placeholder="请输入内容" class="layui-textarea" id="description" name="foodDesc"
                                  required="" lay-verify="description"
                                  autocomplete="off" value=""></textarea>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">
            </label>
            <button class="layui-btn" lay-filter="add" lay-submit="">
                增加
            </button>
            <button type="reset" class="layui-btn layui-btn-primary">
                重置
            </button>
        </div>


    </form>
</div>
<script>

</script>
<script>
    layui.use(['form', 'layer', 'upload'], function () {

        var $ = layui.jquery;
        var form = layui.form,
            layer = layui.layer,
            upload = layui.upload;

        var material_list = [];

        // 获取select选择数据
        $(function () {
            // console.log('start....')
            // 请求cook分类数据
            $.ajax({
                url: '/sell/getAllFoodCookCategory',
                success: function (res) {
                    // console.log(res)
                    var content = '<option value="">烹饪方式</option>';
                    for (var i = 0; i < res.length; i++) {
                        // console.log(res[i])
                        content += "<option value='" + res[i].categoryId + "'>" + res[i].categoryName + "</option>"
                    }
                    // console.log(content)
                    $('#select_c').html(content)
                    form.render('select');
                }
            })

            // 请求type分类数据
            $.ajax({
                url: '/sell/getAllFoodTypeCategory',
                success: function (res) {
                    // console.log(res)
                    var content = '<option value="">荤/素</option>';
                    for (var i = 0; i < res.length; i++) {
                        // console.log(res[i])
                        content += "<option value='" + res[i].categoryId + "'>" + res[i].categoryName + "</option>"
                    }
                    // console.log(content)
                    $('#select_t').html(content)
                    form.render('select');
                }

            });

            // 请求所有食材信息
            $.ajax({
                url: '/sell/showFoodMaterial',
                success: function (res) {
                    console.log(res)
                    var content = '';
                    // <input type="checkbox" name="like[write]" title="猪">
                    for (var i = 0; i < res.data.length; i++) {
                        // console.log(res[i])
                        content += '<input type="checkbox" value="' + res.data[i].materialName + '" name="foodMaterial" title="' + res.data[i].materialName + '">';
                    }
                    // console.log(content);
                    $('#div_material').html(content)
                    form.render();
                }
            });
        });

        // 创建一个上传文件实例
        var uploadInstance = upload.render({
            elem: '#btn1',
            url: '/sell/uploadImage',
            method: 'post',
            accept: 'images',
            acceptMime: 'images/*', // 筛选出文件类型,此为只显示图片文件
            auto: false, // 不自动上传
            bindAction: '#btn2', // 绑定一个按钮触发上传
            choose: function (obj) {
                // 预读本地文件,若是多文件,则会遍历
                obj.preview(function (index, file, result) {
                    // console.log(index); // 文件索引
                    // console.log(file); // 文件对象
                    // console.log(result); // 文件的base64编码

                    $('#span_u').html(file.name)
                    $('#img1').attr('src', result)
                    $('#img1').attr('style', 'width: 6.25rem;height: 6.25rem;')

                    // obj.resetFile(index,file,'123.jpg'); // 重命名文件
                })
            },
            before: function (obj) {
                layer.load(); // loading
            },
            done: function (res) {
                // todo
                layer.closeAll('loading')
                if (res.code == 1) { // 上传 成功
                    $('#input_u').attr('value', res.data)
                    return layer.msg('上传成功！' + res.data)
                } else {
                    return layer.msg('上传失败！')
                }
            },
            error: function (index, upload) {
                layer.closeAll('loading')
                // 失败重传
                var demoText = $('#demoText')
                demoText.html(
                    '<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInstance.upload();
                });
            }
        })

        // 表单渲染
        form.render('select', 'select_type');
        //自定义验证规则
         form.verify({
             name: function(value) {
                 if (value.length <= 1) {
                     return '昵称至少得2个字符';
                 }
                 // 存放结果
                 var result = '';
                 // 访问服务端,不能有重复的菜品名
                 $.ajax({
                     url: '/sell/queryFoodName',
                     async: false,
                     type: 'get',
                     data: {
                         foodName: value
                     },
                     success: function(res) {
                         // 回调方法中return无效
                         if (res == 1) {
                             result = '菜品名已存在，请重新输入！';
                         }
                     },
                     error: function(status) {
                         result = status;
                     }
                 })
                 return result;
             },
             pic: function(value) {
                 if (value.length < 1) {
                     return '请上传图片！'
                 }
             },
             description:function(value){
                 console.log(value.length)
                 if (value.length>255) {
                     return '字数过长，请不要超过255个字！'
                 }
             }
         });

        //监听提交
        form.on('submit(add)', function (data) {

            // 拼接复选框数据
            var material_arr = new Array();
            $("input:checkbox[name='foodMaterial']:checked").each(function (i) {
                material_arr[i] = $(this).val();
            });
            data.field.foodMaterial = material_arr.join(",");

            console.log(data.field);

            //发异步，把数据提交给后端
            $.ajax({
                url: '/sell/addFood',
                type: 'post',
                data: data.field,
                success: function (msg) {
                    // console.log(msg)
                    if (msg == 1) {
                        layer.msg("增加成功！", {
                            icon: 6,
                            time: 1000
                        }, function () {
                            // 获得frame索引
                            var index = parent.layer.getFrameIndex(window.name);
                            // 关闭当前frame
                            parent.layer.close(index);
                            // 可以对父窗口进行刷新
                            x_admin_father_reload();
                        })
                    } else {
                        layer.msg("增加失败！请重试", {
                            icon: 5,
                            time: 1000
                        })
                    }
                }
            })
            return false;
        });
    });
</script>

</body>

</html>
